//
//  searchViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/3/23.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "searchViewController.h"
#import "configddd.h"
#import "searchTableViewCell.h"
#import "searchCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "detailsViewController.h"

@interface searchViewController ()

@end

@implementation searchViewController

- (void)viewWillAppear:(BOOL)animated{

    _searchTextField.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self leftNavHide];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTableviewNotification:) name:@"reloadTableview" object:nil];
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(screenScale(20), 0, screenScale(70), screenScale(30))];
    rightBtn.titleLabel.font = get4sFont(14);
    [rightBtn setTitle:@"取消" forState:UIControlStateNormal];
    [rightBtn setTitleColor:getColor(@"ffffff") forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtnItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtnItem;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(screenScale(288), screenScale(390));
    layout.minimumLineSpacing = screenScale(20);
    layout.minimumInteritemSpacing = screenScale(20);
    
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCollectionView:)];
    self.tableViewTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tableViewTapClick:) ];
    _tableViewTap.cancelsTouchesInView = NO;//设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    self.searchTextField = [[UITextField alloc]init];
    self.historyTableView = [[UITableView alloc]init];
    self.searchCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), scrHeight() - 64) collectionViewLayout:layout];
}

#pragma mark ----------- init ------------

- (void)setSearchTextField:(UITextField *)searchTextField{

    _searchTextField = searchTextField;
    _searchTextField.borderStyle = UITextBorderStyleNone;
    _searchTextField.tintColor = [UIColor blackColor];
    _searchTextField.backgroundColor = getColor(@"ffffff");
    _searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    _searchTextField.layer.cornerRadius = screenScale(15);
    _searchTextField.returnKeyType = UIReturnKeySearch;
    _searchTextField.delegate = self;
    _searchTextField.layer.masksToBounds = YES;
    _searchTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索" attributes:@{NSForegroundColorAttributeName: getColor(@"cecece")}];
    _searchTextField.font = get4sFont(14);
    _searchTextField.frame = CGRectMake(screenScale(20), screenScale(5), screenScale(510), screenScale(60));
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenScale(60), screenScale(70))];
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(screenScale(20), screenScale(20), screenScale(30), screenScale(30))];
    leftView.image = [UIImage imageNamed:@"serach_g"];
    [view addSubview:leftView];
    _searchTextField.leftView = view;
    _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    [self.navigationController.navigationBar addSubview:_searchTextField];
}

- (void)setHistoryTableView:(UITableView *)historyTableView{

    _historyTableView = historyTableView;
    _historyTableView.frame = CGRectMake(0, 0, scrWidth(), scrHeight() - 64);
    _historyTableView.backgroundColor = getColor(@"f3f5f7");
    _historyTableView.delegate = self;
    _historyTableView.dataSource = self;
    _historyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_historyTableView];
    
    [_historyTableView addGestureRecognizer:_tableViewTap];
}

- (void)setSearchCollectionView:(UICollectionView *)searchCollectionView{
    
    _searchCollectionView = searchCollectionView;
    _searchCollectionView.frame = CGRectMake((scrWidth() - 2*screenScale(288))/3, 0, scrWidth() - screenScale(40), scrHeight() - 64);
    _searchCollectionView.delegate = self;
    _searchCollectionView.dataSource = self;
    _searchCollectionView.hidden = YES;
    _searchCollectionView.showsVerticalScrollIndicator = NO;
    _searchCollectionView.backgroundColor = getColor(@"ffffff");
    [_searchCollectionView registerClass:[searchCollectionViewCell class] forCellWithReuseIdentifier:@"collectIdentifier"];
    [self.view addSubview:_searchCollectionView];
    
    [_searchCollectionView addGestureRecognizer:_tap];
}

#pragma mark ----------- reloadTableviewNotification --------------

- (void)reloadTableviewNotification:(NSNotification *)text{

    if ([text.userInfo[@"selected"] isEqualToString:@"yes"]) {
        
        [_historyTableView reloadData];
    }
}

#pragma mark ----------- click -------------

- (void)tableViewTapClick:(id)sender{

    [_searchTextField endEditing:YES];
}

- (void)clickCollectionView:(id)sender{
    
    CGPoint pointTouch = [sender locationInView:_searchCollectionView];
    NSIndexPath *indexPath = [_searchCollectionView indexPathForItemAtPoint:pointTouch];
    
    if (indexPath != nil){
        
        [self collectionView:_searchCollectionView didSelectItemAtIndexPath:indexPath];
    }
    
    [self hideKeyboardClick];
}

- (void)hideKeyboardClick{
    
    [_searchTextField endEditing:YES];
}

- (void)rightBtnClick{

    [_searchTextField removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)deleteBtnClick{

    [PublicFunction saveConfig:nil forKey:@"historyRecord"];
    [_historyTableView reloadData];
}

#pragma mark ------------ UITextFieldDelegate -------------

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (_searchTextField.text.length < 1) {
        
        [PublicFunction showAlert:nil message:@"请输入想要搜索的商品" duration:1.0f];
        
        return NO;
    }

    if (textField == _searchTextField) {
        
        NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
        for (int i = 0; i < arr.count; i ++) {
            
            if ([_searchTextField.text isEqualToString:arr[i]]) {
                
                [arr removeObject:arr[i]];
            }
        }
        [PublicFunction saveConfig:arr forKey:@"historyRecord"];
        
        if (![PublicFunction getConfigWithKey:@"historyRecord"]) {
            
            NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:_searchTextField.text, nil];
            [PublicFunction saveConfig:arr forKey:@"historyRecord"];
        }else{
        
            NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
            [arr insertObject:_searchTextField.text atIndex:0];
            [PublicFunction saveConfig:arr forKey:@"historyRecord"];
        }
        
        [self hideKeyboardClick];
        [textField resignFirstResponder];
        
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        [productParams setValue: _searchTextField.text forKey:@"shop_name"];
        [[MNetworkHandler sharedInstance]conURL:Search
                                    networkType:NetWorkPOST
                                         params:productParams
                                       delegate:nil
                                        showHUD:NO
                                   successBlock:^(id returnData) {
                                       if ([[returnData objectForKey:@"code"]intValue]==1) {
                                           
                                           _historyTableView.hidden = YES;
                                           _searchCollectionView.hidden = NO;
                                           
                                           dataArr = [[NSMutableArray alloc]init];
                                           dataArr = returnData[@"data"];
                                           [_searchCollectionView reloadData];
                                           
                                           NSLog(@"\n\n\n\n\n===returnData===%@",returnData);
                                           
                                       }
                                       else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                           [PublicFunction showAlert:nil message:@"没有搜索到商品" duration:5.0f];
                                       }
                                   } failureBlock:^(NSError *error) {
                                       NSLog(@"%@",error);
                                       [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                   }];
    }
    return YES;
}

#pragma mark -------------------- tableView ----------------------

#pragma mark --- UITableViewDelegate ---

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return screenScale(66);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    NSArray *arr = [[NSArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
    if (arr.count < 1) {
        
        return 0;
    }
    return screenScale(66);
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    NSArray *arr = [[NSArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
    if (arr.count < 1) {
        
        return nil;
    }

    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(66))];
    footerView.backgroundColor = getColor(@"ffffff");
    
    UIButton *deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, scrWidth(), screenScale(66))];
    deleteBtn.titleLabel.font = get4sFont(12);
    [deleteBtn setTitle:@"清除搜索历史" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:getColor(@"757575") forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:deleteBtn];
    
    return footerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"1");
    
    NSArray *arr = [[NSArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
    _searchTextField.text = arr[indexPath.row];
    [self textFieldShouldReturn:_searchTextField];
}

#pragma mark --- UITableViewDataSource ---

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    NSArray *arr = [[NSArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView registerClass:[searchTableViewCell class] forCellReuseIdentifier:@"identifier"];
    searchTableViewCell *cell = (searchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    
    NSArray *arr = [[NSArray alloc]initWithArray:[PublicFunction getConfigWithKey:@"historyRecord"]];
    cell.nameLable.text = arr[indexPath.row];
    
    return cell;
}

#pragma mark -------------------- collectionView ----------------------

#pragma mark --- UICollectionViewDelegate ---

//设置每个 UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(screenScale(288), screenScale(390));
}

//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake((15), 0, 15,0);//上、左、下、右
}

//定义每个UICollectionView 的横向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0;
}


-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    _searchTextField.hidden = YES;
    
    detailsViewController *detailsVC = [[detailsViewController alloc]init];
    detailsVC.hidesBottomBarWhenPushed = YES;
    
    NSDictionary *aDict = dataArr[indexPath.row];
    detailsVC.myStr = [aDict objectForKey:@"shop_id"];
    
    [self.navigationController pushViewController:detailsVC animated:YES];
}

#pragma mark --- UICollectionViewDataSource ---

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return dataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"collectIdentifier";
    searchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
    NSDictionary *dict = dataArr[indexPath.row];
    NSString *urlGood = [dict objectForKey:@"shoppic"];
    NSString *urlN = manage(AP_HOST, urlGood);
    NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *urlW = [NSURL URLWithString:strUrl];
    [cell.imageshow sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
    cell.myLabel.text = [dict objectForKey:@"shop_name"];
    cell.priceLabel.text = [dict objectForKey:@"price"];
    
    return cell;
}

@end
